package com.cheer.ba.presenter.impl;

import android.content.Context;
import android.text.TextUtils;

import com.cheer.ba.R;
import com.cheer.ba.cache.preference.EntityCache;
import com.cheer.ba.cache.preference.Session;
import com.cheer.ba.constant.CodeStatus;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.Constants;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.ReturnCode;
import com.cheer.ba.http.BaseCallback;
import com.cheer.ba.http.CallManager;
import com.cheer.ba.http.Http;
import com.cheer.ba.http.request.APIService;
import com.cheer.ba.model.ArticleModel;
import com.cheer.ba.model.BannerModel;
import com.cheer.ba.model.HotExchangeModel;
import com.cheer.ba.model.HotPlayModel;
import com.cheer.ba.model.PointModel;
import com.cheer.ba.model.ResponseData;
import com.cheer.ba.model.WeatherModel;
import com.cheer.ba.presenter.GeneralPresenter;
import com.cheer.ba.utils.NetUtils;
import com.cheer.ba.view.base.IViewController;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Response;

/**
 * 首页数据处理
 */
public class HomePresenter extends GeneralPresenter {

    private Context mContext;
    private IViewController mView;
    private EntityCache<BannerModel> mBannerCache;
    private EntityCache<HotExchangeModel> mOilCache;
    private EntityCache<ArticleModel> mTodayArticleCache;
    private APIService mUserService;

    //记录当前分页下标
    private int mRecordPage = 0;
    private int mIndex = 0;

    //数据是否加载失败
    private boolean isDataError = false;

    @Override
    public void attachView(IViewController view) {
        this.mView = view;
        mContext = getContext(view);
        mBannerCache = new EntityCache<BannerModel>(mContext, BannerModel.class, "");
        mOilCache = new EntityCache<HotExchangeModel>(mContext, HotExchangeModel.class, "");
        mTodayArticleCache = new EntityCache<ArticleModel>(mContext, ArticleModel.class, "");
        mUserService = Http.getUserService(mContext);
    }

    /**
     * 上传用户经纬度
     */
    public void uploadUserLocation(boolean isShowLoad, String lat, String lon, String prov, String city, String road, String inputMap, String agentType, String locationType) {
        if (!NetUtils.isNetworkConnected(mContext)) {
            mView.onLoadingStatus(mView, true, CodeStatus.Gegeneral.ERROR_NET, CodeStatus.Gegeneral.ERROR_NET, "");
            return;
        }
        if (isShowLoad) {
            mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_LOADING, CodeStatus.Gegeneral.DATA_LOADING, mContext.getString(R.string.data_loading));
        }
        Call<ResponseData> call = mUserService.getUserLocation(1002, Session.getUserId(), lat, lon, prov, city, road, inputMap, agentType, locationType);
        CallManager.add(call);
        call.enqueue(new BaseCallback<ResponseData>() {
            @Override
            public void onResponse(Call<ResponseData> call, Response<ResponseData> response) {
                super.onResponse(call, response);
                if (response.isSuccessful()) {
                    ResponseData res = response.body();
                    if (res.getRet() == ReturnCode.SUCCESS) {
                        mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_SUCCESS_FULL, CodeStatus.Gegeneral.DATA_SUCCESS_FULL, "");
                        return;
                    }
                }
                mView.onLoadingStatus(mView, true, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, "");
            }

            @Override
            public void onFailure(Call<ResponseData> call, Throwable t) {
                super.onFailure(call, t);
                mView.onLoadingStatus(mView, true, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, "");
            }
        });
    }

    /**
     * 获得天气
     */
    public void searchWearth(String cityName, String location) {
        if (!NetUtils.isNetworkConnected(mContext)) {
            mView.onLoadingStatus(mView, true, CodeStatus.Gegeneral.ERROR_NET, CodeStatus.Gegeneral.ERROR_NET);
            return;
        }
        mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_LOADING, CodeStatus.Gegeneral.DATA_LOADING);
        Call<ResponseData<WeatherModel>> call = mUserService.searchWearth(1002, cityName, "", "", "", location);
        CallManager.add(call);
        call.enqueue(new BaseCallback<ResponseData<WeatherModel>>() {
            @Override
            public void onResponse(Call<ResponseData<WeatherModel>> call, Response<ResponseData<WeatherModel>> response) {
                super.onResponse(call, response);
                if (response.isSuccessful()) {
                    ResponseData<WeatherModel> res = response.body();
                    if (res.getRet() == ReturnCode.SUCCESS) {
                        WeatherModel weatherModel = res.getData();
                        if (null != weatherModel) {
                            mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_SUCCESS_FULL, CodeStatus.Gegeneral.DATA_SUCCESS_FULL);
                            mView.updateViewWithTag(weatherModel, ConstantTag.HOME_WEATHER);
                            return;
                        }
                    }
                }
                mView.onLoadingStatus(mView, true, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA);
            }

            @Override
            public void onFailure(Call<ResponseData<WeatherModel>> call, Throwable t) {
                super.onFailure(call, t);
                mView.onLoadingStatus(mView, true, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA);
            }
        });
    }

    /**
     * 获得轮播图
     */
    public void getBanner() {
        if (!NetUtils.isNetworkConnected(mContext)) {
            mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_NET, CodeStatus.Gegeneral.ERROR_NET);
            return;
        }
        Call<ResponseData<List<BannerModel>>> call = mUserService.getBanners(9002);
        CallManager.add(call);
        call.enqueue(new BaseCallback<ResponseData<List<BannerModel>>>() {
            @Override
            public void onResponse(Call<ResponseData<List<BannerModel>>> call, Response<ResponseData<List<BannerModel>>> response) {
                super.onResponse(call, response);
                if (response.isSuccessful()) {
                    ResponseData<List<BannerModel>> res = response.body();
                    if (res.getRet() == ReturnCode.SUCCESS) {
                        List<BannerModel> banners = res.getData();
                        if (null != banners) {
                            if (!banners.isEmpty()) {
                                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_SUCCESS_FULL, CodeStatus.Gegeneral.DATA_SUCCESS_FULL);
                                mView.updateViewWithTag(banners, ConstantTag.HOME_BANNER);
                                try {
                                    mBannerCache.putListEntity(banners);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                mBannerCache.putListEntity(new ArrayList<BannerModel>());
                                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_SUCCESS_NULL, CodeStatus.Gegeneral.DATA_SUCCESS_NULL);
                            }
                            return;
                        }
                    }
                }
                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA);
            }

            @Override
            public void onFailure(Call<ResponseData<List<BannerModel>>> call, Throwable t) {
                super.onFailure(call, t);
                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA);
            }
        });
    }

    /**
     * 获得今日油价信息
     */
    public void getTodayOilPrice(String prov) {
        if (!NetUtils.isNetworkConnected(mContext)) {
            mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_NET, IntentCode.Setting.TODAY_OIL_ERROR);
            mView.updateViewWithTag("", ConstantTag.HOME_OIL_FAIL);
            return;
        }
        Call<ResponseData<List<HotExchangeModel>>> call = mUserService.getTodayOils(9002, prov);
        CallManager.add(call);
        call.enqueue(new BaseCallback<ResponseData<List<HotExchangeModel>>>() {
            @Override
            public void onResponse(Call<ResponseData<List<HotExchangeModel>>> call, Response<ResponseData<List<HotExchangeModel>>> response) {
                super.onResponse(call, response);
                if (response.isSuccessful()) {
                    ResponseData<List<HotExchangeModel>> res = response.body();
                    if (res.getRet() == ReturnCode.SUCCESS) {
                        List<HotExchangeModel> oils = res.getData();
                        if (null != oils) {
                            if (!oils.isEmpty()) {
                                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_SUCCESS_FULL, IntentCode.Setting.TODAY_OIL_SUCCESS);
                                mView.updateViewWithTag(oils, ConstantTag.HOME_OIL);
                                try {
                                    mOilCache.putListEntity(oils);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                mOilCache.putListEntity(new ArrayList<HotExchangeModel>());
                                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_SUCCESS_NULL, IntentCode.Setting.TODAY_OIL_NULL);
                                mView.updateViewWithTag("", ConstantTag.HOME_OIL_FAIL);
                            }
                            return;
                        }
                    }
                }
                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, IntentCode.Setting.TODAY_OIL_ERROR);
                mView.updateViewWithTag("", ConstantTag.HOME_OIL_FAIL);
            }

            @Override
            public void onFailure(Call<ResponseData<List<HotExchangeModel>>> call, Throwable t) {
                super.onFailure(call, t);
                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, IntentCode.Setting.TODAY_OIL_ERROR);
                mView.updateViewWithTag("", ConstantTag.HOME_OIL_FAIL);
            }
        });
    }

    /**
     * 获得今日油讯
     *
     * @param loadMore
     * @param channelId 频道id 1：加油啦频道
     */
    public void getTodayArticles(final boolean loadMore, String channelId) {
        if (!NetUtils.isNetworkConnected(mContext)) {
            mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_NET, CodeStatus.Gegeneral.ERROR_NET, "", loadMore);
            mView.updateViewWithLoadMore("", loadMore, ConstantTag.GET_ARTICLE_FAIL);
            return;
        }
        if (!loadMore) {
            isDataError = false;
            mRecordPage = 0;
        } else {
            if (isDataError) {
                mRecordPage = mIndex;
            } else {
                mRecordPage += Constants.PAGESIZE;
            }
        }
        mIndex = mRecordPage;
        Call<ResponseData<List<ArticleModel>>> call = mUserService.mGetArticles(1508, channelId, mRecordPage, Constants.PAGESIZE);
        CallManager.add(call);
        call.enqueue(new BaseCallback<ResponseData<List<ArticleModel>>>() {
            @Override
            public void onResponse(Call<ResponseData<List<ArticleModel>>> call, Response<ResponseData<List<ArticleModel>>> response) {
                super.onResponse(call, response);
                if (response.isSuccessful()) {
                    ResponseData<List<ArticleModel>> res = response.body();
                    if (res.getRet() == ReturnCode.SUCCESS) {
                        List<ArticleModel> articles = res.getData();
                        if (null != articles) {
                            if (articles.isEmpty()) {
                                isDataError = true;
                                mTodayArticleCache.putListEntity(new ArrayList<ArticleModel>());
                                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_SUCCESS_NULL, CodeStatus.Gegeneral.DATA_SUCCESS_NULL, "", loadMore);
                                mView.updateViewWithLoadMore("", loadMore, ConstantTag.GET_ARTICLE_FAIL);
                            } else {
                                isDataError = false;
                                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_SUCCESS_FULL, CodeStatus.Gegeneral.DATA_SUCCESS_FULL, "", loadMore);
                                mView.updateViewWithLoadMore(articles, loadMore, ConstantTag.GET_ARTICLE_LIST);
                                try {
                                    mTodayArticleCache.putListEntity(articles);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            return;
                        }
                    }
                }
                isDataError = true;
                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, "", loadMore);
                mView.updateViewWithLoadMore("", loadMore, ConstantTag.GET_ARTICLE_FAIL);
            }

            @Override
            public void onFailure(Call<ResponseData<List<ArticleModel>>> call, Throwable t) {
                super.onFailure(call, t);
                isDataError = true;
                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, "", loadMore);
                mView.updateViewWithLoadMore("", loadMore, ConstantTag.GET_ARTICLE_FAIL);
            }
        });
    }

    /**
     * 获得我的订单总额
     */
    public void getMyTotalOrder(String startDate, String endDate) {
        if (!NetUtils.isNetworkConnected(mContext)) {
            mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_NET, CodeStatus.Gegeneral.ERROR_NET);
            mView.updateViewWithTag("", ConstantTag.GET_ORDER_FAIL);
            return;
        }
        Call<ResponseData<PointModel>> call = mUserService.getMyTotalOrder(9002, Session.getUserId(), startDate, endDate);
        CallManager.add(call);
        call.enqueue(new BaseCallback<ResponseData<PointModel>>() {
            @Override
            public void onResponse(Call<ResponseData<PointModel>> call, Response<ResponseData<PointModel>> response) {
                super.onResponse(call, response);
                if (response.isSuccessful()) {
                    ResponseData<PointModel> res = response.body();
                    if (res.getRet() == ReturnCode.SUCCESS) {
                        PointModel model = res.getData();
                        if (null != model) {
                            mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_SUCCESS_FULL, CodeStatus.Gegeneral.DATA_SUCCESS_FULL);
                            mView.updateViewWithTag(model, ConstantTag.GET_ORDER_SUCCESS);
                            return;
                        }
                    }
                }
                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA);
                mView.updateViewWithTag("", ConstantTag.GET_ORDER_FAIL);
            }

            @Override
            public void onFailure(Call<ResponseData<PointModel>> call, Throwable t) {
                super.onFailure(call, t);
                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA);
                mView.updateViewWithTag("", ConstantTag.GET_ORDER_FAIL);
            }
        });
    }

    /**
     * 获得我的总积分
     */
    public void getMyTotalPoint() {
        if (!NetUtils.isNetworkConnected(mContext)) {
            mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_NET, CodeStatus.Gegeneral.ERROR_NET);
            mView.updateViewWithTag("", ConstantTag.GET_POINT_FAIL);
            return;
        }
        Call<ResponseData<PointModel>> call = mUserService.getMyTotalPoint(9002, Session.getUserId());
        CallManager.add(call);
        call.enqueue(new BaseCallback<ResponseData<PointModel>>() {
            @Override
            public void onResponse(Call<ResponseData<PointModel>> call, Response<ResponseData<PointModel>> response) {
                super.onResponse(call, response);
                if (response.isSuccessful()) {
                    ResponseData<PointModel> res = response.body();
                    if (res.getRet() == ReturnCode.SUCCESS) {
                        PointModel model = res.getData();
                        if (null != model) {
                            mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.DATA_SUCCESS_FULL, CodeStatus.Gegeneral.DATA_SUCCESS_FULL);
                            mView.updateViewWithTag(model, ConstantTag.GET_POINT_SUCCESS);
                            return;
                        }
                    }
                }
                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA);
                mView.updateViewWithTag("", ConstantTag.GET_POINT_FAIL);
            }

            @Override
            public void onFailure(Call<ResponseData<PointModel>> call, Throwable t) {
                super.onFailure(call, t);
                mView.onLoadingStatus(mView, false, CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA);
                mView.updateViewWithTag("", ConstantTag.GET_POINT_FAIL);
            }
        });
    }

    /**
     * 获取首页banner缓存数据
     */
    @Override
    public List<BannerModel> getCacheData() {
        return mBannerCache.getListEntity(BannerModel.class);
    }

    /*
    * 获取首页油价缓存数据
     */
    public List<HotExchangeModel> getTodayOilCache() {
        return mOilCache.getListEntity(HotExchangeModel.class);
    }

    /*
    * 获取首页最新资讯缓存数据
    */
    public List<ArticleModel> getTodayArticleCache() {
        return mTodayArticleCache.getListEntity(ArticleModel.class);
    }

    @Override
    public void detachView() {
    }

    /**
     * 获得首页数据
     *
     * @return
     */
    public Object getData(String tag) {
        if (TextUtils.equals(tag, ConstantTag.HOME_TITLE)) {
            //栏目
            List<HotExchangeModel> mRecyclers = new ArrayList<HotExchangeModel>();
            HotExchangeModel model2 = new HotExchangeModel(R.drawable.ic_hom_circle, mContext.getString(R.string.hom_circle));
            HotExchangeModel model = new HotExchangeModel(R.drawable.ic_free_play, mContext.getString(R.string.free_play));
            HotExchangeModel model1 = new HotExchangeModel(R.drawable.ic_oil_navigation, mContext.getString(R.string.oil_navigation));
            HotExchangeModel model3 = new HotExchangeModel(R.drawable.ic_cloud_record, mContext.getString(R.string.ic_cloud_record));
            mRecyclers.add(model2);
            mRecyclers.add(model);
            mRecyclers.add(model1);
            mRecyclers.add(model3);
            return mRecyclers;
        } else if (TextUtils.equals(tag, ConstantTag.HOME_HOT_EXCHANGE)) {
            //热门兑换
            List<HotExchangeModel> mExchanges = new ArrayList<HotExchangeModel>();
            HotExchangeModel model = new HotExchangeModel(R.drawable.ic_exchange_wiper, "雨刷", "400");
            HotExchangeModel model1 = new HotExchangeModel(R.drawable.ic_exchange_wiper, "雨刷", "400");
            HotExchangeModel model2 = new HotExchangeModel(R.drawable.ic_exchange_wiper, "雨刷", "400");
            HotExchangeModel model3 = new HotExchangeModel(R.drawable.ic_exchange_wiper, "雨刷", "400");
            mExchanges.add(model);
            mExchanges.add(model1);
            mExchanges.add(model2);
            mExchanges.add(model3);
            return mExchanges;
        } else if (TextUtils.equals(tag, ConstantTag.HOME_HOT_PLAY)) {
            //热门活动
            List<HotPlayModel> mPlays = new ArrayList<HotPlayModel>();
            HotPlayModel model = new HotPlayModel(R.drawable.ic_hot_play_bg, "现在买卡，即可享受98折优惠！");
            HotPlayModel model1 = new HotPlayModel(R.drawable.ic_hot_play_bg, "现在买卡，即可享受98折优惠！");
            HotPlayModel model2 = new HotPlayModel(R.drawable.ic_hot_play_bg, "现在买卡，即可享受98折优惠！");
            HotPlayModel model3 = new HotPlayModel(R.drawable.ic_hot_play_bg, "现在买卡，即可享受98折优惠！");
            HotPlayModel model4 = new HotPlayModel(R.drawable.ic_hot_play_bg, "现在买卡，即可享受98折优惠！");
            mPlays.add(model);
            mPlays.add(model1);
            mPlays.add(model2);
            mPlays.add(model3);
            mPlays.add(model4);
            return mPlays;
        }
        return null;
    }
}
